<template>
  <view class="page-container">
    <!-- 搜索入口 -->
    <view class="search-bar">
      <navigator url="/pages/home/search/search" class="search-input">
        <uni-icons type="search" size="18" color="#666"></uni-icons>
        <text class="placeholder">搜索养生文章</text>
      </navigator>
    </view>

    <!-- 文章列表 -->
    <scroll-view 
      scroll-y 
      @scrolltolower="loadMore"
      :style="{height: scrollHeight + 'px'}">
      <view v-for="item in list" :key="item.id" class="article-card">
        <image 
          :src="item.cover || '/static/default-cover.png'" 
          mode="aspectFill" 
          class="cover"
          lazy-load></image>
        <view class="content">
          <text class="title">{{item.title}}</text>
          <view class="meta">
            <text class="author">{{item.author}}</text>
            <text class="time">{{item.publishTime}}</text>
          </view>
          <navigator 
            :url="`/pages/home/detail/detail?id=${item.id}`" 
            class="view-detail">
            查看详情
          </navigator>
        </view>
      </view>

      <!-- 加载状态 -->
      <view class="loading-status">
        <text v-if="loading" class="loading-text">加载中...</text>
        <text v-else-if="noMore" class="no-more">- 没有更多内容了 -</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      list: [],
      pageNum: 1,
      pageSize: 10,  // 与接口保持一致
      total: 0,
      loading: false,
      noMore: false,
      scrollHeight: 500
    }
  },
  onLoad() {
    this.calculateHeight()
    this.loadData()
  },
  methods: {
    async loadData() {
      if (this.loading || this.noMore) return
      
      this.loading = true
      try {
        // 使用Promise统一多端返回格式
        const [err, res] = await new Promise(resolve => {
          uni.request({
            url: 'http://localhost:8088/api/articles',
            method: 'GET',
            data: {
              pageNum: this.pageNum,
              pageSize: this.pageSize
            },
            success: (res) => resolve([null, res]),
            fail: (err) => resolve([err, null])
          })
        })

        if (err) throw new Error(`请求失败: ${err.errMsg}`)
        if (res.statusCode !== 200) throw new Error(`接口异常[${res.statusCode}]`)

        const result = res.data
        if (result.code === 200) {
          const payload = result.data
          // 合并数据时使用函数式更新确保响应式
          this.list = this.list.concat(payload.list.map(this.processItem))
          this.total = payload.total
          this.noMore = payload.isLastPage
          this.pageNum = payload.nextPage || this.pageNum + 1
        } else {
          throw new Error(result.message || '业务错误')
        }
      } catch (error) {
        uni.showToast({
          title: error.message.substring(0, 16),
          icon: 'none',
          duration: 2000
        })
        console.error('请求错误:', error)
      } finally {
        this.loading = false
      }
    },
    processItem(item) {
      return {
        ...item,
        title: this.safeTitle(item.title),
        publishTime: this.formatTime(item.publishTime),
        cover: this.validateImage(item.cover)
      }
    },
    safeTitle(title) {
      return (title || '无标题')
        .replace(/\\?"/g, '')  // 处理转义双引号
        .substring(0, 40)
    },
    validateImage(url) {
      return url && url.startsWith('http') ? url : '/static/default-cover.png'
    },
	formatTime(timeStr) {
	  // 空值处理
	  if (!timeStr) return '未知日期';

	  try {
		// 创建日期对象（兼容iOS）
		const date = new Date(timeStr.replace(' ', 'T')); // 处理空格分隔的格式
		
		// 有效性验证
		if (isNaN(date.getTime())) throw new Error('无效日期');

		// 手动格式化年月日
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0'); // 补零
		const day = String(date.getDate()).padStart(2, '0');

		return `${year}-${month}-${day}`;
	  } catch (e) {
		console.warn('日期处理失败:', { input: timeStr, error: e.message });
		return '日期无效';
	  }
	},
    calculateHeight() {
      const systemInfo = uni.getSystemInfoSync()
      const query = uni.createSelectorQuery().in(this)
      query.select('.search-bar').boundingClientRect(res => {
        this.scrollHeight = systemInfo.windowHeight - (res?.height || 0) - 10
      }).exec()
    },
    loadMore() {
      if (!this.loading && !this.noMore) {
        this.loadData()
      }
    }
  }
}
</script>

<style scoped>
/* 保持原有样式不变 */
.search-bar {
  padding: 20rpx 30rpx;
  background: #fff;
}

.search-input {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background: #f5f5f5;
  border-radius: 50rpx;
}

.placeholder {
  color: #666;
  margin-left: 15rpx;
  font-size: 28rpx;
}

.article-card {
  margin: 20rpx;
  padding: 25rpx;
  background: #fff;
  border-radius: 15rpx;
  box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.05);
  display: flex;
}

.cover {
  width: 200rpx;
  height: 200rpx;
  border-radius: 10rpx;
  flex-shrink: 0;
}

.content {
  flex: 1;
  margin-left: 25rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.title {
  font-size: 32rpx;
  color: #333;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.meta {
  font-size: 24rpx;
  color: #999;
  margin-top: 15rpx;
}

.view-detail {
  color: #007AFF;
  font-size: 26rpx;
  margin-top: 20rpx;
}

.loading-status {
  padding: 40rpx 0;
  text-align: center;
}

.loading-text {
  color: #999;
}

.no-more {
  color: #ccc;
}
</style>
